import * as THREE from 'three';
import {DRACOLoader} from "three/examples/jsm/loaders/DRACOLoader";
import * as Cesium from 'cesium'
import {GLTFLoader} from 'three/addons/loaders/GLTFLoader.js';

function addModel(scene) {
    // // 创建圆柱体
    const geometry = new THREE.CylinderGeometry(100, 100, 500, 32);
    const material = new THREE.MeshBasicMaterial({color: 0xff0000});
    const cylinder = new THREE.Mesh(geometry, material);
    // degreeModel(cylinder,113.53233933448793, 41.42128950761943,0)
    const dracoLoader = new DRACOLoader();
    // 设置draco路径
    dracoLoader.setDecoderPath("/public/static/threeJs/draco/");
    dracoLoader.setDecoderConfig({type: "js"});
    dracoLoader.preload();
    // 实例化加载器gltf
    const gltfLoader = new GLTFLoader();
    // 设置gltf加载器draco解码器90
    gltfLoader.setDRACOLoader(dracoLoader);
    // gltfLoader.load("/public/static/threeJs/model/三大顷西.glb", (gltf) => {
    //     scene.add(cylinder);
    //     degreeModel(gltf.scene, 113.52733933448793, 41.42619950761943, -20, 90, 0, 0) // 减小向左 减小向下
    //     gltf.scene.scale.set(100, 100, 100)
    //     gltf.scene.name = '三大顷西'
    //     // gltf.scene.rotation.y = -Math.PI / 2
    //     scene.add(gltf.scene)
    // })
    // gltfLoader.load("/public/static/threeJs/model/小海子.glb", (gltf) => {
    //     scene.add(cylinder);
    //     degreeModel(gltf.scene, 113.81078554418947, 41.425214847023064, -20, 90, 0, 0) // 减小向左 减小向下
    //     gltf.scene.scale.set(100, 100, 100)
    //     gltf.scene.name = '小海子'
    //     // gltf.scene.rotation.x = -Math.PI / 2
    //     scene.add(gltf.scene)
    // })
}

function degreeModel(model, longitude, latitude, height, heading = 0, pitch = 0, roll = 0) {
    // 模型所在位置
    let position = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);
    // 模型的方向
    let hpr = new Cesium.HeadingPitchRoll(
        Cesium.Math.toRadians(heading),
        Cesium.Math.toRadians(pitch),
        Cesium.Math.toRadians(roll),
    )
    // 模型的矩阵
    const modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(position, hpr);
    // 将cesium的矩阵转为three的矩阵
    const threeMatrix = new THREE.Matrix4()
    threeMatrix.fromArray([
        modelMatrix[0], modelMatrix[1], modelMatrix[2], modelMatrix[3],
        modelMatrix[4], modelMatrix[5], modelMatrix[6], modelMatrix[7],
        modelMatrix[8], modelMatrix[9], modelMatrix[10], modelMatrix[11],
        modelMatrix[12], modelMatrix[13], modelMatrix[14], modelMatrix[15],
    ])
    // 调整坐标系对齐
    // 绕x轴旋转90度
    const rotationX = new THREE.Matrix4().makeRotationX(Math.PI / 2);
    // 绕y轴旋转90度
    const rotationY = new THREE.Matrix4().makeRotationY(Math.PI / 2);
    // 将两个矩阵相乘
    threeMatrix.multiply(rotationX).multiply(rotationY);
    // 将变换后的矩阵应用到模型里
    model.matrix.copy(threeMatrix)
    model.matrix.decompose(model.position, model.quaternion, model.scale);
    model.updateMatrixWorld(true);
    return model
}

export {addModel, degreeModel}
